using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Reflection;

namespace AntEater.ComponentModel
{
    /// <summary>
    /// Provides an Iconf for a Class.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
    public sealed class IconAttribute : Attribute
    {

        /// <summary>
        /// Initializes a new instance of the <see cref="T:IconAttribute"/> class.
        /// </summary>
        /// <param name="iconResourceName">Name of the icon resource.</param>
        /// <param name="type">The type whose defining assembly is searched for the icon resource.</param>
        public IconAttribute(Type type, string iconResourceName) {
            this._iconResourceName = iconResourceName;
            this._type = type;
        }

        private string _iconResourceName;

        /// <summary>
        /// Gets the name of the icon resource.
        /// </summary>
        /// <value>The name of the icon resource.</value>
        public string IconResourceName {
            get { return _iconResourceName; }
        }

        private Type _type;

        /// <summary>
        /// Gets or sets the type.
        /// </summary>
        /// <value>The type.</value>
        public Type Type {
            get { return _type; }
        }

        private string _key;

        /// <summary>
        /// Gets or sets an key that can be used for dynamic Image List generation.
        /// </summary>
        /// <value>The key.</value>
        public string Key {
            get { return _key; }
            set { _key = value; }
        }

        /// <summary>
        /// Gets the icon.
        /// </summary>
        /// <value>The icon.</value>
        public Image Icon {
            get {
                Image image = null;
                Assembly assembly = this.Type.Assembly;

                List<string> resourceNames = new List<string>(assembly.GetManifestResourceNames());
                if (resourceNames.Contains(this.IconResourceName)) {
                    using (Stream iconData = assembly.GetManifestResourceStream(this.IconResourceName)) {
                        Icon icon = new Icon(iconData, new Size(16, 16));
                        image = icon.ToBitmap();
                    }
                }

                return image;
            }
        }

    }
}
